/*
 * Demoiselle Framework
 * Copyright (C) 2011 SERPRO
 * ----------------------------------------------------------------------------
 * This file is part of Demoiselle Framework.
 * 
 * Demoiselle Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not,  see <http://www.gnu.org/licenses/>
 * or write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA  02110-1301, USA.
 * ----------------------------------------------------------------------------
 * Este arquivo é parte do Framework Demoiselle.
 * 
 * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou
 * modificá-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação
 * do Software Livre (FSF); na versão 2 da Licença.
 * 
 * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA
 * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou
 * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/GPL em português
 * para maiores detalhes.
 * 
 * Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título
 * "LICENCA.txt", junto com esse programa. Se não, acesse o Portal do Software Público
 * Brasileiro no endereço www.softwarepublico.gov.br ou escreva para a Fundação do Software
 * Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.
 
 * @author Tarcizio Vieira Neto (tarcizio.vieira@owasp.org) <a href="http://www.serpro.gov.br">SERPRO</a>
 * @created 2011
 */
package br.gov.frameworkdemoiselle.security.filter.log;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.owasp.appsensor.APPSENSOR;
import org.owasp.appsensor.AppSensorServiceController;
import org.owasp.appsensor.trendmonitoring.TrendEvent;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Logger;

import br.gov.frameworkdemoiselle.security.UserManager;

/**
 * Servlet Filter implementation class AppSensorLoggerFilter
 */
public class AppSensorLoggerFilter implements Filter {

	private static final String[] obfuscate = { "password" }; //!!!!!!!!!!!!!
	private final Logger logger = ESAPI.getLogger("SecurityFilter");
	
	/**
	 * Default constructor.
	 */
	public AppSensorLoggerFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		//*********************************
		// log this request, obfuscating any parameter named password
		ESAPI.httpUtilities().logHTTPRequest(request, logger, Arrays.asList(obfuscate)); //!!!!		
		//*********************************
		
		//log for trend monitoring
		APPSENSOR.trendLogger().log(
				new TrendEvent(new Date(), request.getRequestURI(), 
						APPSENSOR.asUtilities().getCurrentUser().getAccountName(), 
						request.getRemoteAddr()
				)
		);
		
		if (UserManager.isSessionValid(request)) {
			// is page disabled or active?
			// System.out.println("Filter sees: "+req.getRequestURI());
			boolean isActive = AppSensorServiceController.isServiceActive(request.getRequestURI());
			if (!(isActive)) {
				System.out.println("Not Active, redirecting to locked page");
				Long reactivation = AppSensorServiceController.getServiceReactivationTime(request.getRequestURI(), APPSENSOR.asUtilities().getCurrentUser());
				response.sendRedirect("appsensor_locked.jsp?time=" + reactivation);
				// important: can't add chain.dofilter here. else, blocking by appsensor is negated
			} else { 
				// log the request with appsensor
				AppSensorLogger.log(request);
				// send the user to the page
				chain.doFilter(req, res);
			}
		} else {
			// chain.doFilter(request, response);
			chain.doFilter(req, res);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
